﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using WeixinBusiness.Core;
using WeixinBusiness.Model;
using WeixinBusiness.Model.Enum;

namespace WeixinBusiness
{
    public class WechatAPI
    {
        /// <summary>
        /// 获取微信菜单
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static Menu GetMenu(string accessToken)
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", accessToken);
            HttpWebResponse pos = HttpRequest.CreateGetHttpResponse(url);
            StreamReader sr = new StreamReader(pos.GetResponseStream(), Encoding.UTF8);
            string resultStr = sr.ReadToEnd().Trim();
            Menu result = Newtonsoft.Json.JsonConvert.DeserializeObject<Menu>(resultStr);
            return result;
        }

        /// <summary>
        /// 创建微信菜单
        /// </summary>
        /// <returns></returns>
        public static ResultMsg CreateMenu(string accessToken, Menu menu)
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}", accessToken);

            string json = Newtonsoft.Json.JsonConvert.SerializeObject(menu, new Newtonsoft.Json.JsonSerializerSettings() { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore });
            var client = new WebClient();
            client.Headers["Content-Type"] = "application/json";
            client.Encoding = Encoding.UTF8;
            var strResult = client.UploadString(url, json);
            ResultMsg resultMsg = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultMsg>(strResult);
            return resultMsg;
        }

        /// <summary>
        /// 删除微信菜单
        /// </summary>
        /// <returns></returns>
        public static ResultMsg DeleteMenu(string accessToken)
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={0}", accessToken);
            var client = new WebClient();
            client.Headers["Content-Type"] = "application/json";
            client.Encoding = Encoding.UTF8;
            var strResult = client.UploadString(url, string.Empty);
            ResultMsg resultMsg = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultMsg>(strResult);
            return resultMsg;
        }

        /// <summary>
        /// 发布微信菜单
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string PublishWechatMenu(string accessToken, List<MenuSetting> list)
        {
            var menu = new Menu() { Buttons = new List<Button>() };
            foreach (var item in list.Where(x => string.IsNullOrWhiteSpace(x.ParentId)).OrderBy(x => x.Orderby))
            {
                Button button = new Button();
                button.Name = item.MenuName;
                button.SubButton = new List<Button>();
                switch (item.MenuType)
                {
                    case 1:
                        button.Type = "click";
                        button.Key = item.MenuKey;
                        break;
                    case 2:
                        button.Type = "view";
                        button.Url = item.MenuUrl;
                        break;
                    default:
                        var secondSubButton = new List<Button>();
                        var childMenus = list.FindAll(x => x.ParentId == item.MenuId).OrderBy(x => x.Orderby);
                        foreach (var childItem in childMenus)
                        {
                            var secondButton = new Button();
                            secondButton.Name = childItem.MenuName;
                            switch ((ButtonType)childItem.MenuType)
                            {
                                case ButtonType.Click:
                                    secondButton.Type = ((ButtonType)childItem.MenuType).ToString().ToLower();
                                    secondButton.Key = childItem.MenuKey;
                                    break;
                                case ButtonType.View:
                                    secondButton.Type = ((ButtonType)childItem.MenuType).ToString().ToLower();
                                    secondButton.Url = childItem.MenuUrl;
                                    break;
                            }
                            secondSubButton.Add(secondButton);
                        }
                        button.SubButton.AddRange(secondSubButton);
                        break;
                }
                menu.Buttons.Add(button);
            }
            return CreateMenu(accessToken, menu).Message;
        }
    }
}
